import json

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class YunnanMsrmzfDc21Policy(BaseTaxPolicySpider):
    name = "yunnan_msrmzf_dc21_policy"

    province: str = "云南省"  # 取表格
    city: str = "德宏州"  # 取表格
    county: str = "芒市"  # 取表格
    park: str = "None"  # 取表格
    source: str = "芒市人民政府"  # 取表格 同一个来源合并
    url: str = "https://www.dhms.gov.cn/Web/publice/_M1093_5BG7JLNL4513467577A9452F9F_1.htm"  # 注明入口网址，以便后续排错

    def start_requests(self):
        for url in [
            self.url,
            'https://www.dhms.gov.cn/Web/publice/_M12_4QWSDWW8CE3E8D9EBC2847E2B8_1.htm',
        ]:
            yield scrapy.Request(url, callback=self.parse_list, )

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        elem_list = response.xpath(
            "//ul//li[not(@class)]//a[contains(@href, '.htm') or @title]/ancestor::li[string-length(string(.))>=5] | "
            "//div//dd[not(@class)]//a[contains(@href, '.htm') or @title]/ancestor::dd[string-length(string(.))>=5]")
        print(response.url, len(elem_list))
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            # print(item)
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url'] and 'info' not in item['source_url']:
                continue
            if '/pdf/' in item['source_url'] or '/doc/' in item['source_url'] or '/Web/_F0_0_.htm' in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            if '下页' in response.text or '下一页' in response.text or '»' in response.text:
                next_url = response.xpath("""//a[text()='下页' or text()='下一页' or text()='»' ]/@href""").get()
                if next_url:
                    next_page = response.xpath("""//a[text()='下页' or text()='下一页' or text()='»']/@href""").re_first(r"page=(\d+)&")
                    pages = response.xpath(""".""").re_first(r",第\d+/(\d+)页")
                    for page in range(2, int(pages) + 1):
                        url = next_url.replace(f"page={next_page}&", f"page={page}&")
                        print(response.url, 'next', url)
                        yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})
                else:
                    print('not next_url', response.url)
            else:
                print('not next', response.url)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        item['source'] = self.source
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl yunnan_msrmzf_dc21_policy".split())
